﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ////根据DNS获取域名绑定的IP
            //var address = Dns.GetHostEntry("www.taobao.com").AddressList;

            //foreach (var item in address)
            //{
            //    Console.WriteLine($"淘宝IP:{item}\r\n");
            //}

            //// 字符串转IP地址
            //IPAddress ipaddress = IPAddress.Parse("192.168.10.101");

            //// 通过IP和端口构造IPEndPoint对象,用于远程连接
            //// 通过IP可以确定一台电脑,通过端口可以确定电脑上的一个程序
            //IPEndPoint ipEndPoint = new IPEndPoint(ipaddress, 80);


            //=============SocketClient=================
            Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10086));

            }
            catch (Exception e)
            {
                Console.WriteLine($"连接异常，具体原因：{e.Message}");
            }

            socket.Send(Encoding.UTF8.GetBytes("你好呀!"));

            socket.Send(Encoding.UTF8.GetBytes("你好呀!吃了吗？"));

            socket.Send(Encoding.UTF8.GetBytes("你好呀!睡了吗？"));

            Task.Run(() =>
            {
                Recive(socket);
            });


            Console.ReadKey();

        }

        static void Recive(Socket socket)
        {
            while (true)
            {
                byte[] buffer = new byte[1024 * 1024];
                int readLeng = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                if (readLeng == 0)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    return;
                }

                var serverMsg = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                if (!string.IsNullOrEmpty(serverMsg))
                {
                    Console.WriteLine($"客户端接收到服务端的消息:{serverMsg}");
                }
                else
                {
                    Console.WriteLine("客户端接收到服务端的消息为空!!!");
                }

            }
        }

    }
}
